package com.bawei.park2211a.news

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bawei.base.bean.NewsEntity
import com.bawei.park2211a.R
import com.bawei.park2211a.databinding.ItemNewsBinding
import com.bawei.park2211a.databinding.ItemNoticeBinding
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.chad.library.adapter.base.listener.OnItemLongClickListener

class NewsAdapter : PagingDataAdapter<NewsEntity, NewsAdapter.NewsViewHolder>(diff) {
    private var mOnItemClickListener: OnItemClickListener? = null
    private var mOnItemLongClickListener: OnItemLongClickListener? = null
    companion object {
        var diff = object : ItemCallback<NewsEntity>() {
            override fun areItemsTheSame(oldItem: NewsEntity, newItem: NewsEntity): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: NewsEntity, newItem: NewsEntity): Boolean {
                return oldItem == newItem
            }

        }
    }
    fun setOnItemLongClickListener(listener: OnItemLongClickListener?) {
        this.mOnItemLongClickListener = listener
    }
    fun setOnItemClickListener(listener: OnItemClickListener?) {
        this.mOnItemClickListener = listener
    }
    class NewsViewHolder(itemView: View) : ViewHolder(itemView) {
        val binding: ItemNewsBinding? = DataBindingUtil.bind(itemView)
    }

    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
        val item = getItem(position)!!
        holder.binding?.apply {
            newsMsg.text=item.content
            newsTitle.text=item.title
            newsTime.text=item.publishDate
        }
        holder.itemView.setOnClickListener {
            mOnItemClickListener?.onItemClick( position)
        }
        holder.itemView.setOnLongClickListener {
            mOnItemLongClickListener?.onItemLongClick( position)
            true
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
        return NewsViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_news, parent, false)
        )
    }
    interface OnItemClickListener {
        fun onItemClick( position: Int)
    }
    interface OnItemLongClickListener {
        fun onItemLongClick( position: Int)
    }
}